<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :span="6">
            <a-form-item label="入库单号">
              <a-input placeholder="请输入入库单号" v-model="queryParam.inboundNo"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="物料编码">
              <a-input placeholder="请输入物料编码" v-model="queryParam.materialCode"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="物料名称">
              <a-input placeholder="请输入物料名称" v-model="queryParam.materialName"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="状态">
              <j-dict-select-tag placeholder="请选择状态" v-model="queryParam.status" dictCode="inbound_order_status" />
            </a-form-item>
          </a-col>
          <template v-if="toggleSearchStatus">
            <a-col :span="6">
              <a-form-item label="业务类型">
                <j-dict-select-tag
                  placeholder="请选择业务类型"
                  v-model="queryParam.businessType"
                  dictCode="inventory_business_type"
                />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="业务单号">
                <a-input placeholder="请输入业务单号" v-model="queryParam.businessNo"></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="订单ID">
                <j-select-production-order-modal
                  v-model="queryParam.productionOrderId"
                  :multiple="false"
                  placeholder="请选择订单"
                />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="订单编号">
                <j-select-production-order-modal
                  v-model="queryParam.productionOrderNo"
                  :multiple="false"
                  placeholder="请选择订单编号"
                />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="计划入库时间">
                <a-date-picker
                  style="width: 100%"
                  v-model="queryParam.planInboundTime"
                  placeholder="请选择计划入库日期"
                  format="YYYY-MM-DD"
                />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="实际入库时间">
                <a-date-picker
                  style="width: 100%"
                  v-model="queryParam.actualInboundTime"
                  placeholder="请选择实际入库日期"
                  format="YYYY-MM-DD"
                />
              </a-form-item>
            </a-col>
          </template>
          <a-col :span="6">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button style="margin-left: 8px" @click="searchReset" icon="reload">重置</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button type="primary" icon="plus" @click="handleAdd" v-if="hasPermission('wms:inboundOrder:add')"
        >新增入库单</a-button
      >
      <a-button type="primary" icon="upload" @click="handleImportRemaining" v-if="hasPermission('wms:inboundOrder:add')"
        >导入余料入库单</a-button
      >
      <!-- <a-button type="primary" icon="download" @click="showExportModal" v-if="hasPermission('wms:inboundOrder:export')"
        >导出</a-button
      > -->
      <a-button type="primary" icon="printer" @click="handleBatchPrint" v-if="hasPermission('wms:inboundOrder:print')"
        >批量打印入库单</a-button
      >
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel" v-if="hasPermission('wms:inboundOrder:delete')">
            <a-icon type="delete" />删除
          </a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px">
          批量操作
          <a-icon type="down" />
        </a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div class="table-wrapper">
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
        <i class="anticon anticon-info-circle ant-alert-icon"></i>已选择<a style="font-weight: 600">{{
          selectedRowKeys.length
        }}</a
        >项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        :scroll="{ x: 1800, y: 'calc(100vh - 350px)', scrollToFirstRowOnChange: false }"
        class="inbound-order-table"
        @change="handleTableChange"
      >
        <!-- 物料类型列 -->
        <template slot="materialTypeSlot" slot-scope="text">
          <j-dict-tag :value="text" dictCode="material_type" />
        </template>

        <!-- 业务类型列 -->
        <template slot="businessTypeSlot" slot-scope="text">
          <j-dict-tag :value="text" dictCode="inventory_business_type" />
        </template>

        <!-- 业务单号列 - 支持悬停显示完整内容 -->
        <template slot="businessNoSlot" slot-scope="text">
          <a-tooltip :title="text" placement="topLeft">
            <div class="business-no-cell">{{ text }}</div>
          </a-tooltip>
        </template>

        <!-- 状态列 -->
        <template slot="statusSlot" slot-scope="text">
          <a-tag :color="getStatusColor(text)">
            <j-dict-tag :value="text" dictCode="inbound_order_status" />
          </a-tag>
        </template>

        <!-- 入库凭证列 -->
        <template slot="inboundVoucherSlot" slot-scope="text, record">
          <span v-if="record.inboundVoucher">
            <img
              :src="getImageUrl(record.inboundVoucher)"
              height="40"
              alt="入库凭证"
              @click="handlePreview(record.inboundVoucher)"
              style="cursor: pointer"
              @error="handleImageError"
            />
            <span v-if="getImageCount(record.inboundVoucher) > 1" style="margin-left: 5px">
              +{{ getImageCount(record.inboundVoucher) - 1 }}
            </span>
          </span>
          <span v-else>-</span>
        </template>

        <!-- 操作列 -->
        <span slot="action" slot-scope="text, record">
          <a
            @click="handleEdit(record)"
            v-if="record.status != 4 && record.status != 2 && hasPermission('wms:inboundOrder:edit')"
            >编辑</a
          >
          <!-- 余料入库单显示一键入库按钮 -->
          <a-divider
            type="vertical"
            v-if="record.businessType == 12 && record.status == 1 && hasPermission('wms:inboundOrder:confirm')"
          />
          <a
            @click="handleOneClickInbound(record)"
            v-if="record.businessType == 12 && record.status == 1 && hasPermission('wms:inboundOrder:confirm')"
            >一键入库</a
          >
          <!-- 非余料入库单显示确认入库按钮 -->
          <a-divider
            type="vertical"
            v-if="record.businessType != 12 && record.status == 1 && hasPermission('wms:inboundOrder:confirm')"
          />
          <a
            @click="handleConfirm(record)"
            v-if="record.businessType != 12 && record.status == 1 && hasPermission('wms:inboundOrder:confirm')"
            >确认入库</a
          >
          <a-divider type="vertical" v-if="record.status == 3 && hasPermission('wms:inboundOrder:confirm')" />
          <a @click="handleConfirm(record)" v-if="record.status == 3 && hasPermission('wms:inboundOrder:confirm')"
            >继续入库</a
          >
          <a-divider type="vertical" v-if="record.status == 1 && hasPermission('wms:inboundOrder:cancel')" />
          <a @click="handleCancel(record)" v-if="record.status == 1 && hasPermission('wms:inboundOrder:cancel')"
            >取消</a
          >
          <a-divider type="vertical" v-if="hasPermission('wms:inboundOrder:print')" />
          <a @click="handlePrint(record)" v-if="hasPermission('wms:inboundOrder:print')">打印入库单</a>
          <a-divider type="vertical" v-if="record.inboundVoucher && hasPermission('wms:inboundOrder:printVoucher')" />
          <a
            @click="handlePrintVoucher(record)"
            v-if="record.inboundVoucher && hasPermission('wms:inboundOrder:printVoucher')"
            >打印凭证</a
          >
          <a-divider type="vertical" v-if="record.status == 4 && hasPermission('wms:inboundOrder:delete')" />
          <a-popconfirm
            title="确定删除吗?"
            @confirm="() => handleDelete(record.id)"
            v-if="record.status == 4 && hasPermission('wms:inboundOrder:delete')"
          >
            <a>删除</a>
          </a-popconfirm>
        </span>
      </a-table>
    </div>
    <!-- table区域-end -->

    <!-- 表单区域 -->
    <inbound-order-modal ref="modalForm" @ok="modalFormOk"></inbound-order-modal>
    <inbound-confirm-modal ref="confirmModal" @ok="modalFormOk"></inbound-confirm-modal>
    <inbound-print-modal ref="printModal"></inbound-print-modal>

    <!-- 导入余料入库单模态框 -->
    <a-modal
      title="导入余料入库单"
      :visible="importModalVisible"
      @ok="handleImportConfirm"
      @cancel="handleImportCancel"
      :confirmLoading="importLoading"
      width="1200px"
      :destroyOnClose="true"
    >
      <div v-if="!importData.length">
        <a-upload-dragger
          :fileList="fileList"
          :beforeUpload="beforeUpload"
          :remove="handleRemove"
          accept=".xlsx,.xls"
          :multiple="false"
        >
          <p class="ant-upload-drag-icon">
            <a-icon type="inbox" />
          </p>
          <p class="ant-upload-text">点击或拖拽文件到此区域上传</p>
          <p class="ant-upload-hint">
            支持单个Excel文件上传，文件格式：.xlsx 或 .xls<br />
            请确保Excel文件包含以下列：入库单号、系列、物料名称、物料编码、物料颜色、物料长度、入库数量、订单编号
          </p>
        </a-upload-dragger>
        <div style="margin-top: 16px">
          <a-button type="primary" @click="handleParseFile" :loading="parseLoading" :disabled="!selectedFile">
            解析文件
          </a-button>
        </div>
      </div>

      <div v-else>
        <div style="margin-bottom: 16px">
          <a-alert
            message="文件解析成功"
            :description="`共解析到 ${importData.length} 条数据，请检查数据是否正确`"
            type="success"
            show-icon
          />
        </div>

        <a-table
          :columns="importColumns"
          :dataSource="importData"
          :pagination="false"
          size="small"
          :scroll="{ x: 1200, y: 300 }"
          :rowClassName="getImportRowClassName"
        >
          <!-- 订单编号列 - 支持悬停显示完整内容 -->
          <template slot="orderNoSlot" slot-scope="text">
            <a-tooltip :title="text" placement="topLeft">
              <div class="order-no-cell">{{ text }}</div>
            </a-tooltip>
          </template>
          <template slot="action" slot-scope="text, record, index">
            <a-button type="link" size="small" @click="removeImportRow(index)">删除</a-button>
          </template>
        </a-table>

        <div style="margin-top: 16px">
          <a-button @click="resetImport" style="margin-right: 8px">重新上传</a-button>
        </div>
      </div>
    </a-modal>

    <!-- 图片预览 -->
    <a-modal
      :visible="previewVisible"
      :footer="null"
      @cancel="handleClosePreview"
      width="90%"
      :destroyOnClose="true"
      :maskClosable="true"
      wrapClassName="image-preview-modal"
      :title="`入库凭证预览 (共${previewImages.length}张)`"
    >
      <div class="image-preview-container" tabindex="0" ref="previewContainer" @keydown="handleKeyDown">
        <!-- 视图切换按钮 -->
        <div class="view-toggle-container">
          <a-radio-group v-model="showLargePreview" button-style="solid">
            <a-radio-button :value="false"> <a-icon type="appstore" /> 网格视图 </a-radio-button>
            <a-radio-button :value="true"> <a-icon type="picture" /> 大图视图 </a-radio-button>
          </a-radio-group>
        </div>

        <!-- 图片网格布局 -->
        <div class="image-grid-container" v-show="!showLargePreview">
          <div
            v-for="(image, index) in previewImages"
            :key="index"
            class="image-grid-item"
            :class="{ active: currentImageIndex === index }"
            @click="selectImage(index)"
          >
            <a-spin :spinning="imageLoading" tip="加载中...">
              <img :src="image" alt="入库凭证" @error="handleImageError" @load="handleImageLoad" />
            </a-spin>
            <div class="image-grid-item-index">{{ index + 1 }}</div>
          </div>
        </div>

        <!-- 选中图片大图预览 -->
        <div class="image-preview-selected" v-if="previewImages.length > 0 && showLargePreview">
          <div class="image-slide">
            <a-spin :spinning="imageLoading" tip="图片加载中...">
              <img
                :src="previewImages[currentImageIndex]"
                :style="{ transform: `rotate(${imageRotation}deg) scale(${imageScale})` }"
                alt="入库凭证"
                @error="handleImageError"
                @load="handleImageLoad"
              />
            </a-spin>
          </div>
          <div class="image-preview-counter">{{ currentImageIndex + 1 }}/{{ previewImages.length }}</div>
          <div class="image-preview-controls">
            <a-button-group>
              <a-button icon="zoom-in" @click="zoomIn" title="放大"></a-button>
              <a-button icon="zoom-out" @click="zoomOut" title="缩小"></a-button>
              <a-button icon="fullscreen" @click="toggleFullscreen" title="全屏"></a-button>
              <a-button icon="download" @click="downloadImage" title="下载"></a-button>
              <a-button icon="undo" @click="rotateLeft" title="向左旋转"></a-button>
              <a-button icon="redo" @click="rotateRight" title="向右旋转"></a-button>
              <a-button icon="reload" @click="resetImage" title="重置"></a-button>
            </a-button-group>
            <a-button-group v-if="previewImages.length > 1" style="margin-left: 10px">
              <a-button icon="left" @click="prevImage" title="上一张"></a-button>
              <a-button icon="right" @click="nextImage" title="下一张"></a-button>
            </a-button-group>
            <a-button icon="close" @click="handleClosePreview" style="margin-left: 10px" title="关闭"></a-button>
          </div>
        </div>
      </div>
    </a-modal>

    <!-- 导出类型选择模态框 -->
    <a-modal
      title="选择导出类型"
      :visible="exportModalVisible"
      :confirmLoading="exportLoading"
      @ok="handleExportConfirm"
      @cancel="handleExportCancel"
      width="500px"
      :destroyOnClose="true"
    >
      <div style="padding: 20px 0">
        <a-radio-group v-model="selectedExportType" style="width: 100%">
          <a-radio style="display: block; height: 40px; line-height: 40px" value="order">
            <a-icon type="file-text" style="margin-right: 8px; color: #1890ff" />
            入库单导出:导出入库单基本信息（单号、状态、时间等）
          </a-radio>
          <a-radio style="display: block; height: 40px; line-height: 40px; margin-top: 16px" value="detail">
            <a-icon type="table" style="margin-right: 8px; color: #52c41a" />
            入库明细单导出:导出入库单详细信息（包含物料明细、数量等）
          </a-radio>
        </a-radio-group>
      </div>
    </a-modal>
  </a-card>
</template>

<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import JDictSelectTag from '@/components/dict/JDictSelectTag'
import JDate from '@/components/jeecg/JDate'
import JDictTag from '@/components/dict/JDictTag'
import InboundOrderModal from './modules/InboundOrderModal'
import InboundConfirmModal from './modules/InboundConfirmModal'
import InboundPrintModal from './modules/InboundPrintModal'
import JSelectProductionOrderModal from '@/components/jeecgbiz/JSelectProductionOrderModal'
import JRangeDate from '@/components/jeecg/JRangeDate/JRangeDate'
// 导入postAction
import { deleteAction, getAction, postAction } from '@/api/manage'
import { USER_AUTH, SYS_BUTTON_AUTH } from '@/store/mutation-types'
import 'vue-photo-preview/dist/skin.css'
import preview from 'vue-photo-preview'
import Vue from 'vue'
import moment from 'moment'

// 注册图片预览组件
preview.install(Vue, {
  fullscreenEl: false,
})

export default {
  name: 'InboundOrderList',
  mixins: [JeecgListMixin],
  components: {
    JDictSelectTag,
    JDate,
    JDictTag,
    InboundOrderModal,
    InboundConfirmModal,
    InboundPrintModal,
    JSelectProductionOrderModal,
    JRangeDate,
  },
  data() {
    return {
      description: '入库单管理页面',
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '入库单号',
          align: 'center',
          dataIndex: 'inboundNo',
          width: 160,
        },
        {
          title: '业务类型',
          align: 'center',
          dataIndex: 'businessType',
          width: 100,
          scopedSlots: { customRender: 'businessTypeSlot' },
        },
        // 业务单号
        {
          title: '业务单号',
          align: 'center',
          dataIndex: 'businessNo',
          width: 120,
          scopedSlots: { customRender: 'businessNoSlot' },
        },
        {
          title: '入库凭证',
          align: 'center',
          dataIndex: 'inboundVoucher',
          width: 100,
          scopedSlots: { customRender: 'inboundVoucherSlot' },
        },
        {
          title: '计划入库时间',
          align: 'center',
          dataIndex: 'planInboundTime',
          width: 140,
          customRender: (text) => {
            return text ? moment(text).format('YYYY-MM-DD') : '-'
          },
        },
        {
          title: '实际入库时间',
          align: 'center',
          dataIndex: 'actualInboundTime',
          width: 140,
          customRender: (text) => {
            return text ? moment(text).format('YYYY-MM-DD') : '-'
          },
        },
        {
          title: '总计划入库数量',
          align: 'center',
          dataIndex: 'totalPlanQuantity',
          width: 120,
        },
        {
          title: '总实际入库数量',
          align: 'center',
          dataIndex: 'totalActualQuantity',
          width: 120,
        },
        {
          title: '总成本',
          align: 'center',
          dataIndex: 'totalCost',
          width: 100,
        },
        {
          title: '状态',
          align: 'center',
          dataIndex: 'status',
          width: 100,
          scopedSlots: { customRender: 'statusSlot' },
        },
        {
          title: '创建时间',
          align: 'center',
          dataIndex: 'createTime',
          width: 160,
          sorter: true,
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          width: 160,
          scopedSlots: { customRender: 'action' },
        },
      ],
      url: {
        list: '/wms/inboundOrder/list',
        delete: '/wms/inboundOrder/delete',
        deleteBatch: '/wms/inboundOrder/deleteBatch',
        exportXlsUrl: '/wms/inboundOrder/exportXls',
      },
      dictOptions: {},
      superFieldList: [],
      inboundType: '11', // 默认入库类型：采购入库
      // 权限相关
      permissionList: [],
      // 预览相关
      previewVisible: false,
      previewImage: '',
      previewImages: [], // 用于存储所有预览图片
      currentImageIndex: 0, // 当前显示的图片索引
      imageRotation: 0, // 图片旋转角度
      imageScale: 1, // 图片缩放比例
      imageLoading: false, // 图片加载状态
      showLargePreview: false, // 默认显示网格视图
      selectedImageIndex: -1, // 当前选中的网格图片索引
      // 查询参数
      queryParam: {
        inboundNo: '',
        materialCode: '',
        materialName: '',
        status: '',
        businessType: '',
        businessNo: '',
        planInboundTime: '', // 计划入库时间
        actualInboundTime: '', // 实际入库时间
        productionOrderId: '', // 添加订单ID查询参数
        productionOrderNo: '', // 添加订单编号查询参数
      },
      // 导入相关数据
      importModalVisible: false,
      importLoading: false,
      parseLoading: false,
      fileList: [],
      selectedFile: null,
      importData: [],
      // 导出相关数据
      exportModalVisible: false,
      exportLoading: false,
      selectedExportType: 'order',
      importColumns: [
        { title: '入库单号', dataIndex: 'inboundNo', width: 150 },
        { title: '系列', dataIndex: 'series', width: 150 },
        { title: '物料名称', dataIndex: 'materialName', width: 150 },
        { title: '物料编码', dataIndex: 'materialCode', width: 150 },
        { title: '物料颜色', dataIndex: 'materialColor', width: 150 },
        { title: '物料长度（m）', dataIndex: 'materialLength', width: 150 },
        { title: '入库数量', dataIndex: 'inboundQuantity', width: 150 },
        { title: '订单编号', dataIndex: 'orderNo', width: 150, scopedSlots: { customRender: 'orderNoSlot' } },
        { title: '仓库编号', dataIndex: 'warehouseCode', width: 150 },
        { title: '仓库名称', dataIndex: 'warehouseName', width: 150 },
        { title: '库位编号', dataIndex: 'locationCode', width: 150 },
        { title: '库位名称', dataIndex: 'locationName', width: 150 },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: 80 },
      ],
    }
  },
  created() {
    // 获取字典数据
    this.initDictConfig()
    // 加载权限列表
    this.loadPermissions()
  },
  methods: {
    initDictConfig() {
      // 初始化字典配置
    },
    // 加载权限
    loadPermissions() {
      // 从sessionStorage获取权限
      let authList = JSON.parse(sessionStorage.getItem(USER_AUTH) || '[]')

      // 如果sessionStorage中没有权限，尝试从localStorage获取
      if (!authList || authList.length === 0) {
        authList = JSON.parse(localStorage.getItem(USER_AUTH) || '[]')
      }

      // 从按钮权限中获取
      const buttonAuth = JSON.parse(
        sessionStorage.getItem(SYS_BUTTON_AUTH) || localStorage.getItem(SYS_BUTTON_AUTH) || '[]'
      )

      // 合并权限
      if (buttonAuth && buttonAuth.length > 0) {
        authList = authList.concat(buttonAuth)
      }

      // 提取action字段
      this.permissionList = authList.map((auth) => auth.action || auth)
    },

    // 判断是否有权限
    hasPermission(permission) {
      if (!permission) return true // 如果未指定权限，默认有权限

      // 检查权限列表中是否包含指定权限
      if (this.permissionList.includes(permission)) {
        return true
      }

      // 检查权限列表中是否包含以逗号分隔的多个权限
      for (let perm of this.permissionList) {
        if (perm && perm.includes(',')) {
          const perms = perm.split(',')
          if (perms.includes(permission)) {
            return true
          }
        }
      }

      return false
    },

    // 重写searchReset方法，确保重置productionOrderId字段
    searchReset() {
      this.queryParam = {
        inboundNo: '',
        materialCode: '',
        materialName: '',
        status: '',
        businessType: '',
        businessNo: '',
        planInboundTime: '',
        actualInboundTime: '',
        productionOrderId: '',
        productionOrderNo: '',
      }
      this.loadData(1)
    },

    // 重写getQueryParams方法，处理日期格式
    getQueryParams() {
      // 调用混入的getQueryParams
      let params = Object.assign({}, this.$data.queryParam)

      // 处理日期格式
      if (params.planInboundTime) {
        params.planInboundTime = moment(params.planInboundTime).format('YYYY-MM-DD')
      }

      if (params.actualInboundTime) {
        params.actualInboundTime = moment(params.actualInboundTime).format('YYYY-MM-DD')
      }

      // 分页参数
      params.pageNo = this.ipagination.current
      params.pageSize = this.ipagination.pageSize

      return params
    },

    // 新增入库单
    handleAdd() {
      this.$refs.modalForm.add()
    },
    // 编辑入库单
    handleEdit(record) {
      this.$refs.modalForm.edit(record)
      this.$refs.modalForm.title = '编辑入库单'
    },
    // 确认入库
    handleConfirm(record) {
      this.$refs.confirmModal.confirm(record)
    },
    // 一键入库（余料入库单）
    handleOneClickInbound(record) {
      this.$confirm({
        title: '确认一键入库',
        content: `确定要对入库单 ${record.inboundNo} 执行一键入库操作吗？此操作将直接完成入库并更新库存。`,
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          const url = `/wms/inboundOrder/oneClickInbound?id=${record.id}`
          postAction(url, {})
            .then((res) => {
              if (res.success) {
                this.$message.success('一键入库成功')
                this.loadData()
              } else {
                this.$message.error(res.message || '一键入库失败')
              }
            })
            .catch((error) => {
              console.error('一键入库失败:', error)
              this.$message.error('一键入库失败，请稍后重试')
            })
        },
      })
    },
    // 取消入库单
    handleCancel(record) {
      this.$confirm({
        title: '确认取消',
        content: '确定要取消该入库单吗？取消后将无法恢复。',
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          // 使用URL参数方式调用接口
          const url = `/wms/inboundOrder/cancelInboundOrder?id=${record.id}&remark=用户手动取消`
          postAction(url, {}).then((res) => {
            if (res.success) {
              this.$message.success('取消成功')
              this.loadData()
            } else {
              this.$message.error(res.message || '取消失败')
            }
          })
        },
      })
    },
    // 打印入库单
    handlePrint(record) {
      this.$refs.printModal.show(record.id)
    },
    // 批量打印入库单
    handleBatchPrint() {
      if (this.selectedRowKeys.length === 0) {
        this.$message.warning('请至少选择一条入库单')
        return
      }
      this.$refs.printModal.batchPrint(this.selectedRowKeys)
    },
    // 获取状态颜色
    getStatusColor(status) {
      switch (parseInt(status)) {
        case 1:
          return 'blue' // 待入库
        case 2:
          return 'green' // 已入库
        case 3:
          return 'orange' // 部分入库
        case 4:
          return 'red' // 已取消
        default:
          return 'default'
      }
    },
    // 显示导出类型选择模态框
    showExportModal() {
      if (this.selectedRowKeys.length === 0) {
        this.$message.warning('请先选择要导出的入库单！')
        return
      }
      this.exportModalVisible = true
      this.selectedExportType = 'order'
    },

    // 确认导出
    handleExportConfirm() {
      if (!this.selectedExportType) {
        this.$message.warning('请选择导出类型！')
        return
      }

      this.exportLoading = true

      // 构建导出参数
      const exportParams = {
        ids: this.selectedRowKeys.join(','),
        ...this.queryParam,
      }

      let exportUrl = ''
      let fileName = ''
      if (this.selectedExportType === 'order') {
        exportUrl = '/wms/inboundOrder/exportInboundOrder'
        fileName = '入库单列表'
      } else if (this.selectedExportType === 'detail') {
        exportUrl = '/wms/inboundOrderDetail/exportXls'
        fileName = '入库明细单列表'
      }

      // 调用导出接口
      this.$http
        .get(exportUrl, { params: exportParams, responseType: 'blob' })
        .then((response) => {
          // 创建下载链接
          const blob = new Blob([response.data], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
          })
          const url = window.URL.createObjectURL(blob)
          const link = document.createElement('a')
          link.href = url
          link.download = `${fileName}_${new Date().getTime()}.xlsx`
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
          window.URL.revokeObjectURL(url)

          this.$message.success('导出成功！')
          this.exportModalVisible = false
        })
        .catch((error) => {
          console.error('导出失败:', error)
          this.$message.error('导出失败，请稍后重试！')
        })
        .finally(() => {
          this.exportLoading = false
        })
    },

    // 取消导出
    handleExportCancel() {
      this.exportModalVisible = false
      this.selectedExportType = 'order'
    },

    // 原有导出方法（保留兼容性）
    handleExport() {
      this.showExportModal()
    },

    // 获取图片URL
    getImageUrl(text) {
      if (!text) return ''
      try {
        // 如果text是对象，避免[object Object]错误
        if (typeof text === 'object') {
          console.warn('图片路径不应该是对象:', JSON.stringify(text))
          return ''
        }

        // 检查是否有多个图片路径
        const imageArray = text.split(',')
        if (imageArray && imageArray.length > 0) {
          // 获取第一张图片
          const firstImage = imageArray[0].trim()
          if (!firstImage) return ''

          return window._CONFIG['domianURL'] + '/sys/common/static/' + firstImage
        }
        return ''
      } catch (error) {
        console.error('获取文件URL失败:', error, '原始数据:', text)
        return ''
      }
    },

    // 处理图片加载错误
    handleImageError(event) {
      console.error('图片加载失败', event)
      // 设置为空白图片
      event.target.src =
        ''
      event.target.alt = '图片加载失败'
    },

    // 处理图片加载完成
    handleImageLoad() {
      this.imageLoading = false
    },

    // 获取图片数量
    getImageCount(images) {
      if (!images) return 0

      try {
        // 如果images是对象，避免[object Object]错误
        if (typeof images === 'object') {
          console.warn('图片路径不应该是对象:', JSON.stringify(images))
          return 0
        }

        const imageArray = images.split(',')
        return imageArray.filter((img) => img && img.trim() !== '').length
      } catch (error) {
        console.error('获取图片数量出错:', error)
        return 0
      }
    },

    // 预览图片
    handlePreview(images) {
      if (!images) return

      try {
        // 如果images是对象，避免[object Object]错误
        if (typeof images === 'object') {
          console.warn('预览图片路径不应该是对象:', JSON.stringify(images))
          return
        }

        // 获取所有图片路径
        const imageArray = images.split(',').filter((img) => img && img.trim() !== '')
        if (imageArray.length === 0) return

        // 重置图片变换
        this.imageRotation = 0
        this.imageScale = 1
        this.imageLoading = true // 设置加载状态

        // 构建预览图片列表
        this.previewImages = imageArray.map((img) => {
          const imgPath = img.trim()
          // 使用后端提供的正确URL格式：/sys/common/static/
          const src = window._CONFIG['domianURL'] + '/sys/common/static/' + imgPath

          console.log('预览图片路径:', imgPath, '处理后:', src)
          return src
        })
        this.currentImageIndex = 0 // 重置当前图片索引
        this.previewVisible = true // 显示预览模态框
        this.selectedImageIndex = 0 // 默认选中第一张图片
        this.showLargePreview = imageArray.length === 1 // 如果只有一张图片，直接显示大图预览

        // 添加键盘事件监听
        this.$nextTick(() => {
          if (this.$refs.previewContainer) {
            this.$refs.previewContainer.focus()

            // 监听键盘事件
            window.addEventListener('keydown', this.handleKeyDown)
          }
        })
      } catch (error) {
        console.error('处理预览图片出错:', error, '原始数据:', images)
        this.imageLoading = false
      }
    },

    // 关闭预览模态框时的处理
    handleClosePreview() {
      this.previewVisible = false
      // 移除键盘事件监听
      window.removeEventListener('keydown', this.handleKeyDown)
    },

    // 放大图片
    zoomIn() {
      this.imageScale *= 1.2
      this.applyImageTransform()
    },

    // 缩小图片
    zoomOut() {
      this.imageScale /= 1.2
      this.applyImageTransform()
    },

    // 向左旋转图片
    rotateLeft() {
      this.imageRotation -= 90
      this.applyImageTransform()
    },

    // 向右旋转图片
    rotateRight() {
      this.imageRotation += 90
      this.applyImageTransform()
    },

    // 重置图片变换
    resetImage() {
      this.imageRotation = 0
      this.imageScale = 1
      this.applyImageTransform()
    },

    // 应用图片变换
    applyImageTransform() {
      const img = document.querySelector('.image-preview-selected .image-slide img')
      if (img) {
        img.style.transform = `rotate(${this.imageRotation}deg) scale(${this.imageScale})`
        img.style.maxWidth = this.imageScale > 1 ? 'none' : '100%'
      }
    },

    // 键盘快捷键处理
    handleKeyDown(e) {
      if (!this.previewVisible) return

      switch (e.key) {
        case 'ArrowLeft':
          this.prevImage()
          break
        case 'ArrowRight':
          this.nextImage()
          break
        case 'Escape':
          this.previewVisible = false
          break
        case ' ': // 空格键
          this.toggleViewMode()
          break
      }
    },

    // 上一张图片
    prevImage() {
      if (this.previewImages.length <= 1) return

      let newIndex = this.currentImageIndex - 1
      if (newIndex < 0) {
        newIndex = this.previewImages.length - 1
      }

      this.goToSlide(newIndex)
    },

    // 下一张图片
    nextImage() {
      if (this.previewImages.length <= 1) return

      let newIndex = this.currentImageIndex + 1
      if (newIndex >= this.previewImages.length) {
        newIndex = 0
      }

      this.goToSlide(newIndex)
    },

    // 跳转到指定索引的图片
    goToSlide(index) {
      if (this.currentImageIndex === index) return
      this.currentImageIndex = index
      this.selectedImageIndex = index
      // 重置图片变换
      this.resetImage()
    },

    // 切换视图模式 (网格/大图)
    toggleViewMode() {
      this.showLargePreview = !this.showLargePreview
    },

    // 选中网格图片
    selectImage(index) {
      this.selectedImageIndex = index
      this.currentImageIndex = index
      this.showLargePreview = true // 切换到大图预览
      this.resetImage() // 重置图片变换
    },

    // 切换全屏模式
    toggleFullscreen() {
      const container = document.querySelector('.image-preview-container')
      if (!document.fullscreenElement) {
        if (container.requestFullscreen) {
          container.requestFullscreen()
        } else if (container.mozRequestFullScreen) {
          // Firefox
          container.mozRequestFullScreen()
        } else if (container.webkitRequestFullscreen) {
          // Chrome, Safari
          container.webkitRequestFullscreen()
        } else if (container.msRequestFullscreen) {
          // IE/Edge
          container.msRequestFullscreen()
        }
      } else {
        if (document.exitFullscreen) {
          document.exitFullscreen()
        } else if (document.mozCancelFullScreen) {
          document.mozCancelFullScreen()
        } else if (document.webkitExitFullscreen) {
          document.webkitExitFullscreen()
        } else if (document.msExitFullscreen) {
          document.msExitFullscreen()
        }
      }
    },

    // 下载当前图片
    downloadImage() {
      if (this.previewImages.length === 0) return

      const currentImage = this.previewImages[this.currentImageIndex]
      const link = document.createElement('a')
      link.href = currentImage

      // 从URL中提取文件名
      const fileName = currentImage.split('/').pop() || `入库凭证_${new Date().getTime()}.jpg`
      link.download = fileName

      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },

    // 打印凭证
    handlePrintVoucher(record) {
      if (!record.inboundVoucher) {
        this.$message.warning('没有入库凭证可打印')
        return
      }

      // 获取图片路径
      const imageArray = record.inboundVoucher.split(',').filter((img) => img && img.trim() !== '')
      if (imageArray.length === 0) {
        this.$message.warning('没有有效的入库凭证')
        return
      }

      // 创建新窗口用于打印
      const printWindow = window.open('', '_blank')
      if (!printWindow) {
        this.$message.error('无法打开打印窗口，请检查浏览器是否阻止了弹出窗口')
        return
      }

      // 生成打印内容
      printWindow.document.write('<html><head><title>入库凭证打印</title>')
      printWindow.document.write('<style>')
      printWindow.document.write(`
          body { font-family: Arial, sans-serif; margin: 20px; }
          .header { text-align: center; margin-bottom: 20px; }
          .voucher-container { display: flex; flex-direction: column; align-items: center; }
          .voucher-item { margin-bottom: 20px; page-break-inside: avoid; text-align: center; }
          .voucher-item img { max-width: 100%; max-height: 80vh; }
          .page-break { page-break-after: always; }
          .footer { text-align: center; margin-top: 20px; font-size: 12px; color: #666; }
          @media print {
            .no-print { display: none; }
            @page { margin: 0.5cm; }
          }
        `)
      printWindow.document.write('</style></head><body>')

      // 添加打印按钮
      printWindow.document.write('<div class="no-print" style="text-align: center; margin-bottom: 20px;">')
      printWindow.document.write(
        '<button onclick="window.print();" style="padding: 10px 20px; background-color: #1890ff; color: white; border: none; border-radius: 4px; cursor: pointer;">打印</button>'
      )
      printWindow.document.write(
        '<button onclick="window.close();" style="margin-left: 10px; padding: 10px 20px; background-color: #ff4d4f; color: white; border: none; border-radius: 4px; cursor: pointer;">关闭</button>'
      )
      printWindow.document.write('</div>')

      // 添加标题
      printWindow.document.write('<div class="header">')
      printWindow.document.write(`<h1>入库单 ${record.inboundNo} 凭证</h1>`)
      printWindow.document.write('</div>')

      // 添加凭证图片
      printWindow.document.write('<div class="voucher-container">')
      imageArray.forEach((imgPath, index) => {
        printWindow.document.write('<div class="voucher-item">')

        // 获取完整图片URL
        const imageUrl = window._CONFIG['domianURL'] + '/sys/common/static/' + imgPath.trim()

        // 添加图片
        printWindow.document.write(`<img src="${imageUrl}" alt="入库凭证 ${index + 1}" />`)
        printWindow.document.write(`<p>凭证 ${index + 1}</p>`)
        printWindow.document.write('</div>')

        // 除最后一张图片外，添加分页符
        if (index < imageArray.length - 1) {
          printWindow.document.write('<div class="page-break"></div>')
        }
      })
      printWindow.document.write('</div>')

      // 添加页脚
      printWindow.document.write('<div class="footer">')
      printWindow.document.write(`<p>打印时间: ${new Date().toLocaleString()}</p>`)
      printWindow.document.write('</div>')

      printWindow.document.write('</body></html>')
      printWindow.document.close()

      // 等待图片加载完成后自动打印
      printWindow.onload = function () {
        setTimeout(function () {
          printWindow.focus() // 聚焦打印窗口
          // printWindow.print(); // 如果需要自动打印，取消注释
        }, 1000)
      }
    },

    // 导入余料入库单相关方法
    handleImportRemaining() {
      this.importModalVisible = true
      this.resetImport()
    },

    // 重置导入状态
    resetImport() {
      this.fileList = []
      this.selectedFile = null
      this.importData = []
      this.parseLoading = false
    },

    // 文件上传前处理
    beforeUpload(file) {
      const isExcel =
        file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
        file.type === 'application/vnd.ms-excel'
      if (!isExcel) {
        this.$message.error('只能上传Excel文件！')
        return false
      }

      const isLt10M = file.size / 1024 / 1024 < 10
      if (!isLt10M) {
        this.$message.error('文件大小不能超过10MB！')
        return false
      }

      this.selectedFile = file
      this.fileList = [file]
      return false // 阻止自动上传
    },

    // 移除文件
    handleRemove() {
      this.selectedFile = null
      this.fileList = []
    },

    // 解析Excel文件
    handleParseFile() {
      if (!this.selectedFile) {
        this.$message.warning('请先选择文件')
        return
      }

      this.parseLoading = true
      const formData = new FormData()
      formData.append('file', this.selectedFile)

      postAction('/wms/inboundOrder/parseRemainingMaterialFile', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      })
        .then((res) => {
          if (res.success) {
            this.importData = res.result || []
            if (this.importData.length === 0) {
              this.$message.warning('文件中没有有效数据')
            } else {
              this.$message.success(`成功解析${this.importData.length}条数据`)
            }
          } else {
            this.$message.error(res.message || '文件解析失败')
          }
        })
        .catch((error) => {
          console.error('解析文件失败:', error)
          this.$message.error('文件解析失败，请检查文件格式')
        })
        .finally(() => {
          this.parseLoading = false
        })
    },

    // 删除导入数据行
    removeImportRow(index) {
      this.importData.splice(index, 1)
    },

    // 确认导入
    handleImportConfirm() {
      if (!this.importData.length) {
        this.$message.warning('没有可导入的数据')
        return
      }

      // 检查是否有未绑定库位的物料
      const unboundMaterials = this.importData.filter((item) => !item.warehouseCode || !item.locationCode)

      if (unboundMaterials.length > 0) {
        const materialCodes = unboundMaterials.map((item) => item.materialCode).join(', ')
        this.$error({
          title: '无法导入',
          content: `以下物料编号未绑定库位信息：${materialCodes}。请先在库位管理中为这些物料编号绑定对应的库位后再进行导入。`,
          okText: '知道了',
        })
        return
      }

      this.performImport()
    },

    // 执行导入操作
    performImport() {
      this.importLoading = true
      postAction('/wms/inboundOrder/saveRemainingMaterialInbound', {
        dataList: this.importData,
      })
        .then((res) => {
          if (res.success) {
            this.$message.success('导入成功！')
            this.importModalVisible = false
            this.resetImport()
            this.loadData() // 刷新列表
          } else {
            this.$message.error(res.message || '导入失败')
          }
        })
        .catch((error) => {
          console.error('导入失败:', error)
          this.$message.error('导入失败，请稍后重试')
        })
        .finally(() => {
          this.importLoading = false
        })
    },

    // 获取导入表格行样式类名
    getImportRowClassName(record) {
      // 如果没有仓库编号或库位编号，则标红显示
      if (!record.warehouseCode || !record.locationCode) {
        return 'import-row-error'
      }
      return ''
    },

    // 取消导入
    handleImportCancel() {
      this.importModalVisible = false
      this.resetImport()
    },
  },
}
</script>

<style scoped>
.ant-card-body .table-operator {
  margin-bottom: 18px;
}
.ant-table-tbody .ant-table-row td {
  padding-top: 8px;
  padding-bottom: 8px;
}
.anty-row-operator button {
  margin: 0 5px;
}
.ant-btn-danger {
  background-color: #ffffff;
}
.ant-modal-cust-warp {
  height: 100%;
}
.ant-modal-cust-warp .ant-modal-body {
  height: calc(100% - 110px) !important;
  overflow-y: auto;
}
.ant-modal-cust-warp .ant-modal-content {
  height: 90% !important;
  overflow-y: hidden;
}
.table-wrapper {
  position: relative;
  height: calc(100vh - 280px);
  overflow: hidden;
}
.inbound-order-table {
  margin-top: 10px;
}
.inbound-order-table .ant-table-fixed-header .ant-table-scroll .ant-table-header {
  overflow: hidden;
  height: auto;
}
.inbound-order-table .ant-table-body {
  overflow-x: auto !important;
}
.inbound-order-table .ant-table-thead > tr > th {
  background-color: #f5f5f5;
  font-weight: bold;
}
.inbound-order-table .ant-table-tbody > tr:hover > td {
  background-color: #e6f7ff;
}

/* 图片预览相关样式 */
.image-preview-container {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  outline: none; /* 移除focus时的轮廓线 */
}
.image-preview-container .image-slide {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.image-preview-container .image-slide img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
  transition: transform 0.3s ease;
}
.image-preview-container .image-preview-counter {
  position: absolute;
  top: 10px;
  right: 10px;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  padding: 5px 10px;
  border-radius: 5px;
  font-size: 14px;
  z-index: 10;
}
.image-preview-container .image-preview-controls {
  position: absolute;
  bottom: 10px;
  left: 50%;
  transform: translateX(-50%);
  background-color: rgba(0, 0, 0, 0.5);
  padding: 8px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  z-index: 10;
  transition: opacity 0.3s ease;
}
.image-preview-container:not(:hover) .image-preview-controls {
  opacity: 0.6;
}
.image-preview-container .image-preview-controls .ant-btn {
  color: white;
  background: transparent;
  border-color: #d9d9d9;
}
.image-preview-container .image-preview-controls .ant-btn:hover {
  color: #1890ff;
  background: rgba(255, 255, 255, 0.2);
}

/* 模态框样式 */
.image-preview-modal .ant-modal-content {
  background-color: rgba(0, 0, 0, 0.85);
}
.image-preview-modal .ant-modal-close {
  color: white;
}
.image-preview-modal .ant-modal-body {
  padding: 24px;
}

/* 网格视图样式 */
.image-grid-container {
  display: grid;
  grid-template-columns: repeat(5, 1fr); /* 默认每行5张图片 */
  gap: 15px; /* 图片之间的间距 */
  justify-content: center;
  padding: 15px;
  overflow-y: auto; /* 允许网格内容滚动 */
  max-height: 500px; /* 网格容器最大高度 */
  background-color: #f5f5f5;
  border-radius: 4px;
}

/* 响应式布局 */
@media screen and (max-width: 1600px) {
  .image-grid-container {
    grid-template-columns: repeat(4, 1fr); /* 较小屏幕每行4张图片 */
  }
}
@media screen and (max-width: 1200px) {
  .image-grid-container {
    grid-template-columns: repeat(3, 1fr); /* 平板每行3张图片 */
  }
}
@media screen and (max-width: 768px) {
  .image-grid-container {
    grid-template-columns: repeat(2, 1fr); /* 手机每行2张图片 */
  }
}

.image-grid-item {
  width: 100%;
  aspect-ratio: 1/1; /* 保持正方形 */
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2px solid #eee;
  border-radius: 4px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.2s ease;
  background-color: #fff;
  position: relative;
}
.image-grid-item.active {
  border-color: #1890ff;
  box-shadow: 0 0 10px rgba(24, 144, 255, 0.5);
}
.image-grid-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
.image-grid-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.image-grid-item-index {
  position: absolute;
  top: 5px;
  right: 5px;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
}

.view-toggle-container {
  display: flex;
  justify-content: center;
  margin-bottom: 15px;
}

.image-preview-selected {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 10px;
  background-color: #000; /* 大图预览背景 */
}
.image-preview-selected .image-slide {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.image-preview-selected .image-slide img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
  transition: transform 0.3s ease;
}
.image-preview-selected .image-preview-counter {
  position: absolute;
  top: 10px;
  right: 10px;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  padding: 5px 10px;
  border-radius: 5px;
  font-size: 14px;
  z-index: 10;
}
.image-preview-selected .image-preview-controls {
  position: absolute;
  bottom: 10px;
  left: 50%;
  transform: translateX(-50%);
  background-color: rgba(0, 0, 0, 0.5);
  padding: 8px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  z-index: 10;
  transition: opacity 0.3s ease;
}
.image-preview-selected:not(:hover) .image-preview-controls {
  opacity: 0.6;
}
.image-preview-selected .image-preview-controls .ant-btn {
  color: white;
  background: transparent;
  border-color: #d9d9d9;
}
.image-preview-selected .image-preview-controls .ant-btn:hover {
  color: #1890ff;
  background: rgba(255, 255, 255, 0.2);
}

/* 订单编号单元格样式 - 只显示首行，其余隐藏 */
.order-no-cell {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 100px;
  line-height: 1.5;
  cursor: pointer;
}

/* 业务单号单元格样式 - 只显示首行，其余隐藏 */
.business-no-cell {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 100px;
  line-height: 1.5;
  cursor: pointer;
}

/* 导入表格错误行样式 - 无仓库库位信息的物料标红显示 */
.import-row-error {
  background-color: #fff2f0 !important;
  border-left: 3px solid #ff4d4f;
}

.import-row-error:hover {
  background-color: #ffebe8 !important;
}

.import-row-error td {
  color: #cf1322;
}
</style>